package com.geo.geotool.controller;

import com.geo.geotool.base.entity.RetEntity;
import com.geo.geotool.base.entity.RetResponse;
import com.geo.geotool.entity.geo.GeoFileInfo;
import com.geo.geotool.service.IGeoFileService;
import com.geo.geotool.service.geofile.ShapeFileParser;
import com.geo.geotool.util.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

/**
 * • @Description: 地理文件解析
 * • @author  : yell
 * • @date : 2021/11/24  11:16
 */
@RestController
@RequestMapping("/geoFileParser")
@Slf4j
public class GeoFileParserController {
    @Value("${resultPath}")
    String resultPath;

    @Autowired
    IGeoFileService geoFileParser;
    @Value("${downloadUrl}")
    String downloadUrl;
    @RequestMapping("/geoFileParse")
    @ResponseBody
    public Map parserGeoShp(@RequestParam("Type")String type,@RequestParam("FileValues") String fileValues,
                                  @RequestParam("SRType") String sRType,@RequestParam("SkipFrzn") String skipFrzn,
                                  @RequestParam("f")String f) throws Exception{
        String txtPath = geoFileParser.parserFileToTxt(type,fileValues);
        Map resultMap = new HashMap();
        resultMap.put("ProcessState",true);
        resultMap.put("ProcessValue",downloadUrl + txtPath);
        return resultMap;
    }


    @RequestMapping("/shape")
    @ResponseBody
    public RetEntity handleFileUpload(@RequestParam("file") MultipartFile[] files) throws Exception{
        try {
            // 将上传的文件保存到临时文件中
            Path tempDir = Files.createTempDirectory("shapefile");
            for (MultipartFile file : files) {
                Path tempFile = tempDir.resolve(file.getOriginalFilename());
                try (InputStream inputStream = file.getInputStream()) {
                    Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
                }
            }
            String filename = files[0].getOriginalFilename();
            int lastIndex = filename.lastIndexOf('.');
            String nameWithoutExtension = filename.substring(0, lastIndex);
            String filePath  =  tempDir.toFile().getAbsolutePath() + File.separator + nameWithoutExtension + ".shp";
            // 处理Shapefile文件
            ShapeFileParser shapeFileParser = new ShapeFileParser();
            GeoFileInfo geoFileInfo = shapeFileParser.parserFile(filePath);
            return RetResponse.makeOKRsp(geoFileInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return RetResponse.makeErrRsp("文件上传失败");
        }
    }


    @RequestMapping("/download")
    public void download(@RequestParam("path") String path, HttpServletResponse response) {
        try {
            // path是指想要下载的文件的路径
            File file = new File(resultPath+File.separator+path);
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);

                // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
